package com.seaboxdata.kafka;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.stereotype.Component;

/**
 * 海康开放平台KAFKA客户端
 *
 * @author
 * @create 2020-08-28 10:20
 **/
@Component
public class BaseHikvisionKafkaConsumer {

    private Map<String, KafkaConsumer<String, String>> consumers;

    private static final boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");

    private Properties props = new Properties();

    private String servers = "172.21.112.139:9092";

    private String acks = "all";

    private Integer retries = 0;

    private Integer batchSize = 16384;

    private String keySerializer = "org.apache.kafka.common.serialization.StringSerializer";

    private String valueSerializer = "org.apache.kafka.common.serialization.StringSerializer";

    public BaseHikvisionKafkaConsumer() {
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ProducerConfig.ACKS_CONFIG, acks);
        props.put(ProducerConfig.RETRIES_CONFIG, retries);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        consumers = new HashMap<>();
    }

    public KafkaConsumer<String, String> getConsumer(String topic) {

        if (isWin) {
            //如果是windows指定本地的配置文件,本地调试使用
        }
        //props.put("security.protocol", "SASL_PLAINTEXT");
        //props.put("sasl.kerberos.service.name", "kafka");
        // props.put("sasl.mechanism", "GSSAPI");

        if (consumers.get(topic) == null) {
            props.put(ConsumerConfig.GROUP_ID_CONFIG, topic);
            KafkaConsumer<String, String> stringStringKafkaConsumer = new KafkaConsumer<>(props);
            stringStringKafkaConsumer.subscribe(Collections.singletonList(topic));
            consumers.put(topic, stringStringKafkaConsumer);
            return stringStringKafkaConsumer;
        } else {
            return consumers.get(topic);
        }
    }
}
